<template>
  <!-- 空间信息展示（只有在上传到空间时展示） -->
  <div v-if="spaceId">
    <a-row class="space-container">
      <!-- 空间名称 -->
      <a-col :span="16">
        <a-typography-title style="font-size: 20px; font-family: YRDZST, serif"
        >{{ space.spaceName }}
        </a-typography-title>
      </a-col>
      <!-- 已用空间和图片数量 -->
      <a-col :span="8" class="stats">
        <a-flex vertical class="stat-item">
          <span style="margin-right: 4px; text-align: right !important">已用空间</span>
          <span class="space-usage">
            {{ formatSize(space.totalSize) }} / {{ formatSize(space.maxSize) }}
          </span>
        </a-flex>
        <a-flex vertical class="stat-item">
          <span style="text-align: right !important">图片数量</span>
          <span class="pic-count">{{ space.totalCount }} / {{ space.maxCount }}</span>
        </a-flex>
      </a-col>
    </a-row>
  </div>

  <div id="picture-add">
    <!-- 动态布局：根据是否上传成功切换 -->
    <div v-if="!picture" class="upload-only-layout">
      <h2 class="page-title">
        {{ route.query?.id ? '修改图片' : '创建图片' }}
      </h2>
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="file" tab="本地上传">
          <div class="upload-card">
            <PictureUpload
              :picture="picture"
              :on-success="(newPicture) => handleUploadSuccess(newPicture, 'file')"
              class="picture-upload"
              :spaceId="spaceId"
            />
          </div>
        </a-tab-pane>
        <a-tab-pane key="url" tab="URL 上传">
          <div class="url-upload-card">
            <UrlPictureUpload
              :picture="picture"
              :on-success="(newPicture) => handleUploadSuccess(newPicture, 'url')"
              class="url-picture-upload"
              :spaceId="spaceId"
            />
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <div v-else class="main-layout">
      <!-- 左侧上传区 -->
      <div class="upload-section">
        <div class="upload-card">
          <PictureUpload
            v-if="methodUpload === 'file'"
            :picture="picture"
            :on-success="(newPicture) => handleUploadSuccess(newPicture, 'file')"
          />
        </div>
      </div>

      <!-- 新增：按钮 + 表单的垂直布局容器 -->
      <div class="button-form-wrapper">
        <!-- 编辑按钮（保持原有逻辑） -->
        <div class="picture-button">
          <a-space>
            <a-button
              v-if="picture"
              :icon="h(EditOutlined)"
              type="primary"
              class="submit-btn"
              style="background-color: blueviolet !important"
              @click="doEditPicture"
            >
              修改图片
            </a-button>
            <a-button
              v-if="picture"
              :icon="h(CreditCardOutlined)"
              type="primary"
              class="submit-btn"
              style="background-color: #f85a5a !important"
              @click="doOutPaintingPicture"
            >
              AI 扩图
            </a-button>
          </a-space>
        </div>

        <!-- 右侧表单区 -->
        <div class="form-section">
          <a-form
            layout="vertical"
            :model="pictureForm"
            @finish="handlePictureSubmit"
            class="info-form"
          >
            <a-form-item label="名称" name="name" class="form-item">
              <a-input
                v-model:value="pictureForm.name"
                placeholder="请输入图片名称"
                class="form-input"
              />
            </a-form-item>
            <a-form-item label="简介" name="introduction" class="form-item">
              <a-textarea
                v-model:value="pictureForm.introduction"
                placeholder="请输入图片简介（可选）"
                :rows="2"
                autoSize
                allowClear
                class="form-textarea"
              />
            </a-form-item>
            <a-form-item label="分类" name="category" class="form-item">
              <a-auto-complete
                v-model:value="pictureForm.category"
                placeholder="请选择或输入分类"
                allowClear
                :options="categoryOptions"
                class="form-input"
              />
            </a-form-item>
            <a-form-item label="标签" name="tags" class="form-item">
              <a-select
                v-model:value="pictureForm.tags"
                mode="tags"
                placeholder="请输入标签（按回车添加）"
                allowClear
                :options="tagOptions"
                class="form-select"
              />
            </a-form-item>

            <a-form-item class="form-item submit-item">
              <a-space>
                <a-button type="primary" html-type="submit" class="submit-btn"> 提交</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </div>

    <!-- 图片裁剪器 -->
    <PictureCropper
      ref="imageCropperRef"
      :imageUrl="picture?.url"
      :picture="picture as API.PictureVO"
      :spaceId="spaceId"
      :space="space"
      :onSuccess="onCropSuccess"
    />

    <!-- AI 扩图 -->
    <PictureAiOutPainting
      ref="imageOutPaintingRef"
      :picture="picture as API.PictureVO"
      :spaceId="spaceId"
      :onSuccess="onOutPaintingSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import PictureUpload from '@/components/PictureUpload.vue'
import { computed, h, onMounted, reactive, ref, watchEffect } from 'vue'
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet
} from '@/api/pictureController'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController'
import { formatSize } from '@/util'
import PictureCropper from '@/components/PictureCropper.vue'
import { CreditCardOutlined, EditOutlined } from '@ant-design/icons-vue'
import PictureAiOutPainting from '@/components/PictureAiOutPainting.vue'

const router = useRouter()
const route = useRoute()

// ---------- 空间信息模块 ---------------
// 接收传来的空间 id
const spaceId = computed<string | undefined>(() => {
  const id = route.query?.spaceId
  if (typeof id === 'string' && id.trim() !== '') {
    return id
  }
  return undefined
})

// 获取当前的空间信息
// --------- 获取空间详情 -------------
const space = ref<API.SpaceVO>({})
// 根据空间id获取详情
const fetchSpaceById = async () => {
  if (spaceId.value != null) {
    try {
      const res = await getSpaceVoByIdUsingGet({
        // @ts-ignore
        id: spaceId.value
      })
      if (res.data?.code === 0 && res.data?.data) {
        space.value = res.data.data
      } else {
        message.error('加载空间详情失败: ' + res.data?.message)
      }
    } catch (error: any) {
      message.error('加载空间详情失败: ' + error.message)
    }
  }
}
// 空间详情加载完毕以及空间 id 改变时执行
watchEffect(() => {
  // 获取当前空间信息
  fetchSpaceById()
})

// ---------- 上传图片模块 ---------------
// 核心状态：控制布局切换
const picture = ref<API.PictureVO | null>(null)
// 创建图片时切换布局
const activeKey = ref<'file' | 'url'>('file')
const methodUpload = ref<'file' | 'url'>('file')

// 上传成功回调：设置 picture 触发布局切换
const handleUploadSuccess = (newPicture: API.PictureVO, method: 'file' | 'url') => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
  methodUpload.value = method
}

// 表单数据初始化
const pictureForm = reactive<API.PictureEditDTO>({})

// 创建图片时表单提交
const handlePictureSubmit = async (values: any) => {
  if (!picture.value?.id) return

  const res = await editPictureUsingPost({
    id: picture.value.id,
    spaceId: spaceId.value,
    ...values
  })

  if (res.data?.code === 0 && res.data?.data) {
    message.success('操作成功')
    if (picture.value.spaceId) {
      await router.push(`/space/${picture.value.spaceId}`)
    } else {
      await router.push(`/picture/${picture.value.id}`)
    }
  } else {
    message.error('操作失败: ' + res.data?.message)
  }
}

// 分类标签和图片标签
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])

// 获取分类标签和图片标签
const getPictureTagCategory = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data?.code === 0 && res.data?.data) {
    // @ts-ignore
    categoryOptions.value = (res.data.data.categoryList ?? []).map((category) => ({
      value: category,
      label: category
    }))
    // @ts-ignore
    tagOptions.value = (res.data.data.tagList ?? []).map((tag) => ({
      value: tag,
      label: tag
    }))
  } else {
    message.error('加载标签失败: ' + res.data?.message)
  }
}

// 编辑回显 调用编辑页面时显示
const editPicture = async () => {
  const id = route.query?.id as string
  if (id) {
    // @ts-ignore
    const res = await getPictureVoByIdUsingGet({ id: id as string })
    if (res.data?.code === 0 && res.data?.data) {
      picture.value = res.data.data
      pictureForm.name = res.data.data.name
      pictureForm.introduction = res.data.data.introduction
      pictureForm.category = res.data.data.category
      pictureForm.tags = res.data.data.tags
    } else {
      message.error('加载图片失败: ' + res.data?.message)
    }
  }
}

// 初始化, 页面挂载时
onMounted(() => {
  // 加载标签
  getPictureTagCategory()
  // 修改图片的信息
  editPicture()
})

// ------------ 图片裁剪模块 ---------------
// 图片编辑弹窗引用
const imageCropperRef = ref()

// 编辑图片
const doEditPicture = () => {
  if (imageCropperRef.value) {
    imageCropperRef.value.openModal()
  }
}

// 编辑成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

// ------------ AI 扩图模块 ---------------
// 图片编辑弹窗引用
const imageOutPaintingRef = ref()

// 打开 AI 扩图的弹窗
const doOutPaintingPicture = () => {
  if (imageOutPaintingRef.value) {
    imageOutPaintingRef.value.openModal()
  }
}

// 扩图保存成功的回显
const onOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}
</script>

<style scoped>
/* 基础容器 */
#picture-add {
  max-width: 1200px;
  margin: 40px auto;
  padding: 30px 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/*上传空间顶部展示*/
.space-container {
  background-color: rgb(225, 238, 223);
  margin: 40px auto;
  padding: 12px 20px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 100px;
  max-width: 1200px;
}

.stats {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  color: #666; /* 文字颜色，可按需调整 */
}

.stat-item {
  display: flex;
  align-items: center;
  /* 关键：内部文本也不换行 */
  white-space: nowrap;
  /* 可选：溢出隐藏，避免挤压时混乱 */
  overflow: hidden;
  text-overflow: ellipsis;
}

.space-usage,
.pic-count {
  display: flex;
  align-items: center;
}

/* 单栏上传布局 */
.upload-only-layout {
  text-align: center;
}

/* 标题通用样式 */
.page-title {
  margin: 0 0 30px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.picture-upload {
  width: 100%;
  min-height: 200px;
}

.upload-section {
  width: 45%;
  display: flex; /* 新增 */
  flex-direction: column; /* 新增 */
  background-color: #e1eedf; /* 新增，与表单背景色一致 */
  border-radius: 8px; /* 新增，与表单圆角一致 */
  padding: 10px; /* 新增，与表单内边距一致 */
}

/* 上传区通用样式 */
.upload-card {
  background-color: transparent; /* 修改，移除原有背景色 */
  border-radius: 8px;
  padding: 0; /* 修改，移除原有内边距 */
  transition: all 0.3s ease;
  margin-bottom: 0; /* 修改，移除底部边距 */
  flex: 1; /* 新增，使卡片填充剩余空间 */
  display: flex; /* 新增 */
  flex-direction: column; /* 新增 */
  justify-content: center; /* 新增，垂直居中 */
  align-items: center; /* 新增，水平居中 */
}

.upload-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.upload-card :deep(.ant-upload) {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 左右布局（上传成功后） */
/* 调整主布局的高度 */
.main-layout {
  display: flex;
  gap: 20px;
  min-height: 600px; /* 新增，确保有足够的高度 */
}

/* 新增：按钮 + 表单的垂直布局容器 */
.button-form-wrapper {
  display: flex;
  flex-direction: column; /* 垂直排列 */
  gap: 16px;              /* 按钮与表单的间距 */
  width: 55%;
}

/* 编辑按钮 */
.picture-button{
  min-height: 100px;
  text-align: center;
  background-color: #e1eedf;
  border-radius: 12px;
}

.form-section {
  width: 100%;
  background-color: #e1eedf;
  border-radius: 8px;
  padding: 25px;
}

/* 表单项 */
.form-item {
  margin-bottom: 20px !important;
}

/* 输入框 */
.form-input,
.form-textarea,
.form-select {
  border-radius: 6px !important;
  border-color: #e5e7eb !important;
  transition: all 0.2s ease;
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
  border-color: #4caf50 !important;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1) !important;
}

/* 按钮 */
.submit-item {
  display: flex;
  justify-content: center;
  padding: 0 10px; /* 增加左右内边距，防止边缘溢出 */
}

.submit-btn {
  margin-top: 32px;
  height: 36px !important;
  font-size: 14px !important;
  font-weight: bold;
  background-color: #4caf50 !important;
  border-radius: 12px !important;
  transition: all 0.3s ease !important;
  width: 80%; /* 使用相对宽度，占父容器80% */
  max-width: 320px; /* 最大宽度限制，保持大屏幕下的美观 */
  min-width: 150px; /* 最小宽度限制，防止过小导致文字溢出 */
}

/* 调整按钮间距 */
:deep(.ant-space-item) {
  margin-right: 10px !important; /* 两个按钮之间的间距 */
}

/* 响应式 */
@media (max-width: 992px) {
  .submit-btn {
    width: 100%; /* 小屏幕下占满父容器宽度 */
    font-size: 13px !important; /* 适当缩小字体 */
  }

  .main-layout {
    flex-direction: column;
  }

  .upload-section,
  .button-form-wrapper {
    width: 100%; /* 小屏幕下占满宽度 */
  }
  .form-section {
    width: 100%;
  }
}
</style>
